//
//  MyURLConnectionDelegate.m
//  YuiKe
//
//  Created by yuike5 yuike5 on 11-11-8.
//  Copyright (c) 2011年 yuike. All rights reserved.
//

#import "MyURLConnectionDelegate.h"
#import "mcf.h"

@implementation MyURLConnectionDelegate
@synthesize data=_data;
@synthesize statusCode=_statusCode;
@synthesize delegate=_delegate;



-(void) dealloc
{
    YRelease(_data)
    
    [super dealloc];
}


- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)aResponse
{
    NSHTTPURLResponse *resp = (NSHTTPURLResponse*)aResponse;
    if (resp) {
        _statusCode = resp.statusCode;
    } else {
        _statusCode = -1;
    }
    if (_data) {
        [_data release];
        _data = nil;
    }
	_data = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data
{
	[_data appendData:data];
}

- (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error
{ 
    if (_data) {
        [_data release];
        _data = nil;
    }
    
    NSString* msg = [NSString stringWithFormat:@"Error: %@ %@",
                     [error localizedDescription],
                     [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
    
    NSLog(@"Connection failed: %@", msg);
    [_delegate URLConnectionDidFailWithError:error];
}



- (void)connectionDidFinishLoading:(NSURLConnection *)aConn
{    
    NSString* msg = [[[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding] autorelease];
    
    [_delegate URLConnectionDidFinishLoading: msg];    
    if (_data) {
        [_data release];
        _data = nil;
    }
}


@end
